import { transObjToSearch } from '../util'

const $fetch = function () {
  return $fetch.request.apply($fetch, arguments)
}

const options = {
  baseUrl: '',
  method: 'post',
  headers: {
    'Content-type': 'application/x-www-form-urlencoded'
  },
  credentials: 'include',
  body: {}
}

$fetch.default = options
$fetch.interceptors = {
  request: req => req,
  response: res => JSON.stringify(res)
}

$fetch.request = function (url, options) {
  const config = $fetch.default
  const requestOptions = {
    url: config.baseUrl + url,
    ...Object.assign(config, options)
  }
  return Promise.resolve($fetch.interceptors.request(requestOptions))
    .then(({ url, ...options }) => {
      const request = new window.Request(url, options)
      return window.fetch(request).then($fetch.interceptors.response)
    })
}

$fetch.post = function (url, data, headers = {}) {
  return $fetch.request(url, { headers, method: 'post', body: transObjToSearch(data) })
}

$fetch.postJSON = function (url, data, headers) {
  let json = data
  if (typeof data === 'object') json = JSON.stringify(data)
  return $fetch.request(url, {
    headers: { 'Content-type': 'application/json', ...headers },
    method: 'post',
    body: json
  })
}

$fetch.get = function (url, params, headers) {
  url += `?${transObjToSearch(params)}`
  return $fetch.request(url, { headers, method: 'get' })
}

$fetch.put = function (url, data, headers) {
  return $fetch.request(url, { headers, method: 'put', body: data })
}

$fetch.del = function (url, data, headers) {
  return $fetch.request(url, { headers, method: 'delete', body: data })
}

$fetch.interceptor = function (request, response) {
  if (request) $fetch.interceptors.request = request
  if (response) $fetch.interceptors.response = response
  return $fetch
}

export default function initFetch (Hero) {
  Hero.fetch = $fetch
}

Object.seal(options)
Object.seal($fetch)
